<?php

namespace App\Modules\Apicrzs\Services\Water;

use App\Exceptions\Exception;
use App\Library\Pay\AliPayService;
use App\Library\Wechat\PayWeChatApi;
use App\Library\Junda\src\Consumption;
use App\Library\Junda\src\EquipmentService;
use App\Modules\Admin\Entities\Equipment\EquipmentParamsFreeModel;
use App\Modules\Admin\Entities\Member\UserCardModel;
use App\Modules\Admin\Entities\Water\WaterDeviceModel;
use App\Modules\Admin\Entities\Water\WaterOrderModel;
use App\Modules\Apicrzs\Entities\UsersModel;
use App\Modules\Apicrzs\Services\BaseServices;
use App\Modules\Apicrzs\Services\WeChat\WechatPayService;
use App\Traits\CryptAES;
use App\Traits\Users\UserCardTrait;
use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class WaterOrderService extends BaseServices
{

    use UserCardTrait;
    public function __construct(WaterOrderModel $model)
    {
        $token = \request()->header('token');
        $user_info = CryptAES::decryptToken($token, 'user_grzq');
        $this->user_id = $user_info['data']['user_id'] ?? 0;
        $this->model = $model;
    }

    /**
     *  扫码 订单创建
     * @param $params
     * @return array|false
     */
    public function createScanOrder($params)
    {
        $openid = $params['openid'] ?? "";
        $fee_id = $params['fee_id'] ?? "";
        $pay_type = $params['pay_type'] ?? "online_card";
        if ($params['pay_type']=='success_wx'){
            $pay_type = 'weixin';
        }elseif ($params['pay_type']=='alipay'){
            $pay_type='alipay';
        }else{
            $pay_type = 'card';
        }
        if (!$fee_id) {
            $this->error = '参数错误';
            return false;
        }

        xdebug($params,'参数','equipment');

        $card_no = $params['card_no'] ?? "";

        if(Cache::has('water:device:equipment_params:free:'.$fee_id)){
            $paramsFreeInfo = Cache::get('water:device:equipment_params:free:'.$fee_id);
            $equipment_id = $paramsFreeInfo['equipment_id'];
            $equipment_info = Cache::get('water:device:job_cache:eq_all:'.$equipment_id);
        }else {
            $fee_water_info = EquipmentParamsFreeModel::getInstance()->getEquipmentParamsFreeCache(false);

            $paramsFreeInfo = $fee_water_info['free'][$fee_id];
        }
//        $paramsFreeInfo = EquipmentParamsFreeModel::getInstance()->getFreeByid($fee_id);

        $equipment_id = $paramsFreeInfo['equipment_id'];
        $water_title = $paramsFreeInfo['water_title'];
        //xdebug($paramsFreeInfo,'设备','equipment/'.$equipment_water_title);

        $money = $paramsFreeInfo['money'];
        if ($pay_type == 'card') {
            //水卡  直接打水
            if ($card_no) {
                $freshCard = UserCardModel::getInstance()->getUserByCardNo($card_no);
                if ($freshCard) {
                    UserCardModel::getInstance()->updateUserByCardNo($card_no, ['water_id' => $paramsFreeInfo['water_id']]);
                    if ($freshCard['remaining_value'] < $money) {
                        $this->error = '余额不足';
                        return false;
                    }
                    $valueBefore = $freshCard['remaining_value'];
                    $valueAfter = $valueBefore - $money;
                    $this->VirtulCardConsume($equipment_id, $card_no);
                    $this->error = '正常打水';
                    return ['code'=>100,'data'=>[]];
                }
            }
        } else {
            // 微信 创建订单  支付
            $wx_res =  $this->createOrderPayWx($paramsFreeInfo, $params);

            xdebug($wx_res,'微信 创建订单','equipment/'.$water_title);
            return ['code'=>200,'data'=>$wx_res];
        }
    }

    /**
     *  创建订单  微信支付
     * @param $paramsFreeInfo
     * @param $params
     * @return array|false
     * @throws Exception
     */
    public function createOrderPayWx($paramsFreeInfo,$params)
    {
        $openid = $params['openid']??"";
        $fee_id = $params['fee_id']??"";
        $log_id = $params['log_id']??0;
        $user_id = $this->user_id??0;
        if ($user_id){
           $user_info =  UsersModel::getInstance()->user_info($user_id);
            $openid = $user_info['open_id'];
        }

        $money = $paramsFreeInfo['money'];

        if ($params['pay_type']=='success_wx'){
            $pay_type = 'weixin';
        }elseif ($params['pay_type']=='alipay'){
            $pay_type='alipay';
        }else{
            $pay_type = 'card';
        }

        if (!$fee_id){
            $this->error = '参数错误';
            return false;
        }
        $card_no = $params['card_no']??"";
        $order_no = $this->model->findAvailableNo();
        $description =  $paramsFreeInfo['water_title'] ;
        $order_insert = [
            'user_card_id' => $freshCard['user_card_id'] ?? 0,
            'water_id' => $paramsFreeInfo['water_id'],
            'apparatus_type' => $paramsFreeInfo['ttype'],
            'openid' => $openid,
            'user_id' => $user_id,
            'card_no' => $card_no,
            'coupon_id' => 0,
            'order_sn' => $order_no,
            'type' => $params['type'],
            'total_price' => $money,//应收金额
            'buy_money' => $money,//应收金额
            'amount' => $money,
            'value_before' => 0,
            'value_after' => 0,
            'pay_type' => $pay_type,
            'usage_type' => $params['usage_type'] ?? '',
            'operator_name' => $user_id,
            'remark' => $params['remark'] ?? $description,
            'log_id' => $log_id
        ];
        DB::beginTransaction();
        try{
            $this->detail = $this->model->create($order_insert);
            DB::commit();
            $this->error='提交成功';
            return [
                'openid'=>$this->detail['openid'],
                'order_id'=>$this->detail['order_id'],
                'order_sn'=>$this->detail['order_sn'],
                'remark'=>$this->detail['remark'],
                'amount'=>$money,
            ];
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }


    /**
     *  微信支付 参数
     * @param $params
     * @return array|mixed[]
     */
    public function paymentOrder($params)
    {

        xdebug(request()->header(),'微信支付 01 ','','params_pay');
        $order_sn = $params['order_sn'];
        $openid = $params['openid']??"";
        $order_info  = $this->model->getWaterOrderByOrderSn($order_sn);
        $free_id = $order_info['free_id'];
        $user_id = $this->user_id??0;
        if ($user_id){
            $user_info =  UsersModel::getInstance()->user_info($user_id);
            $openid = $user_info['open_id'];
        }
        $pay_array['openid'] = $openid;
        $pay_array['order_sn'] = $order_sn;
        $pay_array['amount'] = $order_info['total_price'];
        $pay_array['description'] = $order_info['remark'];
        $pay_array['attach'] = ['type'=>"water_consume"];
        if ($order_info['pay_type']=='weixin'){
            $pay_service = new WechatPayService();
            $res_pay = $pay_service->wx_pay('consume', $pay_array);
            $res_pay['order_sn'] = $order_sn;
        }elseif ($order_info['pay_type'] =='alipay'){
            $res_pay = AliPayService::instance()->create($order_info['remark'],$order_sn,$order_info['buy_money'],$order_info['remark']);

        }else{
            $res_pay['order_sn'] = $order_sn;
        }
        return $res_pay;
    }
    /**
     * 扫码 支付 使用卡内余额
     * @param $params
     * @return void
     */
    public function getScanOnlineConsumeStart($params)
    {

        $order_sn = $params['order_sn'];
        $pay_type = $params['pay_type'];

        xdebug($params,'扫码 支付 使用卡内余额-1','demo');
        if ($params['pay_type']=='success_wx'){
            $pay_type = 'weixin';
        }elseif ($params['pay_type']=='alipay'){
            $pay_type='alipay';
        }else{
            $pay_type = 'card';
        }
        $order_info = $this->model->getWaterOrderByOrderSn($order_sn);
        $paramsFreeInfo = EquipmentParamsFreeModel::getInstance()->getWaterDeviceIdByType($order_info['water_id'],$order_info['apparatus_type']);
        $equipment_id = $paramsFreeInfo['equipment_id'];


        xdebug($paramsFreeInfo,'扫码 支付 使用卡内余额-2','demo');

        if ($order_info['card_no']){
            $card_no = $order_info['card_no'];
            $this->VirtulCardConsume($equipment_id,$card_no);
            $this->model->updateWaterOrderByOrderSn($order_sn,[
                'pay_type'=>'card',
                'pay_time'=>time(),
                'payment_method'=>$pay_type,
                'status'=>0,
                'is_delete'=>0,
                'desc'=>"IC 扫码",
            ]);
        }else{
            if ($order_info['is_water']==1){
                $this->error ='当前订单已打水完成';
                return false;
            }
            $this->model->updateWaterOrderByOrderSn($order_sn,[
                'pay_type'=>$pay_type,
                'pay_time'=>time(),
                'status'=>1,
            ]);

            xdebug($order_info,'扫码 支付 使用卡内余额-3','demo');
            $this->IssueOnlineConsume($paramsFreeInfo['equipment_id'],$paramsFreeInfo['money']*100,$order_sn);
        }

        xdebug($params,'使用卡内余额','online');
        $this->error = "下发成功，点击按键取水";
        return true;
    }
    /**
     *  IC 卡  取水
     * @param $params
     * @return array
     */
    public function getScanConsume($params){
        $equipment_id = $params['equipment_id'];
        $card_no = $params['card_no'];
        $res_junda  = $this->getUserCardByCardCode($card_no);
        if ($res_junda['code']!==100){
            return ['code'=>101,'msg'=>$res_junda['msg']];
        }
        $IssueOnline = $this->VirtulCardConsume($equipment_id,$card_no);
        if (!$IssueOnline['isIssue'] ){
            return ['code'=>101,'msg'=>'下发指令失败，网络异常或者水机状态异常'];
        }

        $IssueOnline['card_code']=$card_no;
        $IssueOnline['equipment_id']=$equipment_id;
        xdebug($IssueOnline,'IC 卡 取水','','IC');
        return ['code'=>100,'data'=>$IssueOnline];
    }

    /**
     * IC 卡
     *  下发指令 - 开始取水
     * @param $equipment_id
     * @param $money
     * @param $order_no
     */
    public function VirtulCardConsume($equipment_id,$card_no)
    {
        // 下发 指令取水
        $IssueOnline =  Consumption::VirtulCardConsume($equipment_id,$card_no);

        if (!$IssueOnline['success']){
            $this->error = "下发成功，点击按键取水";
            return true;
        }
        return $IssueOnline;
    }
    /**
     *  本平台 数据
     *  下发指令 - 开始取水
     * @param $equipment_id
     * @param $money
     * @param $order_no
     */
    public function IssueOnlineConsume($equipment_id,$money,$order_no)
    {
        // 下发 指令取水
        $IssueOnline =  EquipmentService::IssueOnlineConsume($equipment_id,$money,$order_no);


        xdebug($IssueOnline,'本平台 数据','online');
        if ($IssueOnline['success']){
            $this->error = "下发成功，点击按键取水";
            return true;
        }
        return $IssueOnline;
    }

    public function paymentOrderCancel($params)
    {
        $order_sn =intval($params['order_sn']);
        $desc =$params['desc']??"";
        $this->model->updateWaterOrderByOrderSn($order_sn,['status'=>-1,'desc'=>$desc]);


        return true;
    }

}
